package cn.loioi.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.web.socket.client.standard.WebSocketContainerFactoryBean;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

import cn.loioi.websocket.WebSocketHandler;
import cn.loioi.websocket.WebSocketHandshakeInterceptor;
import cn.loioi.websocket.pool.ConnecttionPool;

@Order(4)
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

	@Override
	public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
		registry.addHandler(webSocketHandler(), "/socket/test").addInterceptors(webSocketHandshakeInterceptor()).withSockJS();
	}

	@Bean
	public WebSocketContainerFactoryBean createWebSocketContainer() {
		WebSocketContainerFactoryBean containerFactoryBean = new WebSocketContainerFactoryBean();
		containerFactoryBean.setMaxTextMessageBufferSize(8192);
		containerFactoryBean.setMaxBinaryMessageBufferSize(8192);
		return containerFactoryBean;
	}

	@Bean("cn.loioi.websocket.pool.ConnecttionPool")
	public ConnecttionPool connecttionPool() {
		ConnecttionPool connecttionPool = new ConnecttionPool();
		return connecttionPool;
	}

	@Bean("cn.loioi.websocket.WebSocketHandler")
	public WebSocketHandler webSocketHandler() {
		return new WebSocketHandler(connecttionPool());
	}

	@Bean("cn.loioi.websocket.WebSocketHandshakeInterceptor")
	public WebSocketHandshakeInterceptor webSocketHandshakeInterceptor() {
		return new WebSocketHandshakeInterceptor();
	}
}
